﻿
using Commons;
using Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Model;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using WebApp.Models;

namespace WebApp.ApiControllers
{
    /// <summary>
    /// 地址管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    public class AddressController : Controller
    {
        private readonly IBaseService _baseService;
        private readonly Logger log = LogManager.GetCurrentClassLogger();
        /// <summary>
        /// 地址信息
        /// </summary>
        /// <param name="baseService"></param>
        public AddressController(IBaseService baseService)
        {
            _baseService = baseService;
        }
        /// <summary>
        /// 新增收货地址
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultModel AddWxAddress(T_Address address)
        {
            ResultModel result = new ResultModel();
            try
            {
                //判断地址是否存在
                Expression<Func<T_Address, bool>> isExists = PredicateExtensionses.True<T_Address>();
                isExists = isExists.And(i => i.UserId == address.UserId)
                    .And(i => i.Name == address.Name)
                    .And(i => i.Province == address.Province)
                    .And(i => i.City == address.City)
                    .And(i => i.County == address.County)
                    .And(i => i.CountyCode == address.CountyCode) 
                    .And(i => i.Detail == address.Detail)
                    .And(i => i.Phone == address.Phone ); 
                T_Address t_address = _baseService.GetModel(isExists);
                if (t_address == null)
                {
                    _baseService.Insert(address);
                }
                result.code = "200";
                result.result = (int)MsgType.success;
                result.type = MsgType.success.ToString();
                result.msg = "地址添加成功";
            }
            catch (Exception ex)
            {
                log.Error(ex, ex.Message);
                result.msg = ex.Message;
            }
            return result;
        }
    }
}
